//
//  MineCartViewController.m
//  copyrightTrading
//
//  Created by 郭子一 on 2020/10/6.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "MineCartViewController.h"
#import "MineCartCell.h"
@interface MineCartViewController ()<UITableViewDelegate,UITableViewDataSource,MineCartCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *selectAllBtn;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) UIButton *payOrDeleteBtn; // 结算/删除按钮
@property (nonatomic, strong) NSMutableArray *selectArray; // 选中的
@property (nonatomic, strong) NSMutableArray *allIDArray; // 全部的id数组，用来跟选中的id做比较的
@property (nonatomic, strong) NSMutableArray *dataArray; //
@property (nonatomic, assign) BOOL isEditing; // 删除还是结算(是右上角管理按钮控制的,如果是选中状态，就是要删除，否则就是结算)
@property (nonatomic, strong) NSDecimalNumber *moneyString; //
@end

@implementation MineCartViewController

- (NSMutableArray *)selectArray
{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

- (NSMutableArray *)allIDArray
{
    if (!_allIDArray) {
        _allIDArray = [NSMutableArray array];
    }
    return _allIDArray;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    for (int i = 0; i < 16; i ++) {
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//        [self.dataArray addObject:indexPath];
//    }
    self.moneyString = [NSDecimalNumber decimalNumberWithString:@"0"];
}

- (void)setupUI
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = RGB_VALUE(0xDC0000);
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(Height_NavBar);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"whiteBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [headerView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-14);
        make.left.offset(18);
        make.width.height.mas_equalTo(16);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"购物车";
    titleLabel.font = JSS_MEDIUM_FONT(17);
    titleLabel.textColor = RGB_VALUE(0xFFFFFF);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-9);
        make.centerX.offset(0);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(24);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"管理" forState:UIControlStateNormal];
    [loginBtn setTitle:@"完成" forState:UIControlStateSelected];
    [loginBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:JSS_MEDIUM_FONT_7];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.width.mas_equalTo(72);
        make.right.offset(-2);
        make.height.mas_equalTo(22);
    }];
    
    UIView *bottomView = [UIView new];
//    bottomView.backgroundColor = RGB_VALUE(0xDC0000);
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.offset(0);
        make.height.mas_equalTo(Height_TabBar);
    }];
    
    self.selectAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.selectAllBtn setTitle:@"全选" forState:UIControlStateNormal];
    [self.selectAllBtn setTitleColor:RGB_VALUE(0x989898) forState:UIControlStateNormal];
    [self.selectAllBtn setImage:[UIImage imageNamed:@"MineCartCircle"] forState:UIControlStateNormal];
    [self.selectAllBtn setImage:[UIImage imageNamed:@"MineCartSelect"] forState:UIControlStateSelected];
    [self.selectAllBtn.titleLabel setFont:JSS_MEDIUM_FONT_4];
    [self.selectAllBtn addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.selectAllBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleLeft imageTitleSpace:8];
    [bottomView addSubview:self.selectAllBtn];
    [self.selectAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(13);
        make.left.offset(27);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(24);
    }];
    
    self.moneyLabel = [UILabel new];
    self.moneyLabel.text = @"";
    self.moneyLabel.font = JSS_MEDIUM_FONT(17);
    self.moneyLabel.textColor = RGB_VALUE(0x989898);
    self.moneyLabel.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:self.moneyLabel];
    [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.selectAllBtn);
        make.centerX.offset(0);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(24);
    }];
    NSString *priceString = [NSString stringWithFormat:@"合计：0元"];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceString];
    [string addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:118/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(2, 2)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(4, 1)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(0, 3)];
    self.moneyLabel.attributedText = string;
    
    self.payOrDeleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.payOrDeleteBtn setTitle:@"结算" forState:UIControlStateNormal];
    [self.payOrDeleteBtn setTitleColor:RGB_VALUE(0x000000) forState:UIControlStateNormal];
    [self.payOrDeleteBtn.titleLabel setFont:JSS_MEDIUM_FONT_4];
    [self.payOrDeleteBtn addTarget:self action:@selector(payOrDeleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.payOrDeleteBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [bottomView addSubview:self.payOrDeleteBtn];
    [self.payOrDeleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.selectAllBtn);
        make.right.offset(-34);
        make.width.mas_equalTo(28);
        make.height.mas_equalTo(20);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[MineCartCell class] forCellReuseIdentifier:@"MineCartCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(headerView.mas_bottom).offset(0);
        make.bottom.offset(-Height_TabBar);
    }];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self requestCartData];
}

- (void)requestCartData
{
    [self.allIDArray removeAllObjects];
    [self.selectArray removeAllObjects];
    self.moneyString = [NSDecimalNumber decimalNumberWithString:@"0"];
    NSString *priceString = [NSString stringWithFormat:@"合计：0元"];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceString];
    [string addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:118/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(2, 2)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(4, 1)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(0, 3)];
    self.moneyLabel.attributedText = string;
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"cartlist" parameters:@{} done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        self.dataArray = responseObject[@"data"][@"cart_list"];
        for (NSDictionary *dic in self.dataArray) {
            [self.allIDArray addObject:dic[@"id"]];
        }
        [self.tableView reloadData];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

- (void)backBtnClick
{
    [self pop];
}

// 管理完成
- (void)loginBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.isEditing = YES; // 要删除购物车数据
        [self.payOrDeleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        self.moneyLabel.hidden = YES;
    } else {
        self.isEditing = NO;  // 要结算购物车数据
        [self.payOrDeleteBtn setTitle:@"结算" forState:UIControlStateNormal];
        self.moneyLabel.hidden = NO;
    }
    
}

// 全选
- (void)selectAllBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
//        for (int i = 0; i < 16; i ++) {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//            [self.selectArray addObject:indexPath];
//        }
        for (NSDictionary *dic in self.dataArray) {
            [self.selectArray addObject:dic[@"id"]];
        }
        [self.tableView reloadData];
        self.moneyString = [NSDecimalNumber decimalNumberWithString:@"0"];
        for (NSDictionary *dic in self.dataArray) {
            NSDecimalNumber *priceToadd = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",dic[@"price"]]];
            self.moneyString = [self.moneyString decimalNumberByAdding:priceToadd];
        }
        NSString *priceString = [NSString stringWithFormat:@"合计：%@元",[self.moneyString stringValue]];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceString];
        [string addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:118/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(2, [[self.moneyString stringValue] length] + 1)];
        [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange([[self.moneyString stringValue] length]+3, 1)];
        [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(0, 3)];
        self.moneyLabel.attributedText = string;
    } else {
        [self.selectArray removeAllObjects];
        [self.tableView reloadData];
        self.moneyString = [NSDecimalNumber decimalNumberWithString:@"0"];
        NSString *priceString = [NSString stringWithFormat:@"合计：%@元",[self.moneyString stringValue]];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceString];
        [string addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:118/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(2, [[self.moneyString stringValue] length] + 1)];
        [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange([[self.moneyString stringValue] length]+3, 1)];
        [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(0, 3)];
        self.moneyLabel.attributedText = string;
    }
    
}

// 删除或者是结算按钮
- (void)payOrDeleteBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (self.isEditing) { // 删除
        [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"delcart" parameters:@{@"id":self.selectArray} done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            [self requestCartData];
        } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
        }];
    } else { // 结算
        NSDictionary *paramDic = @{
            @"order_type":@"2",
            @"ids":self.selectArray,
            @"price":self.moneyString, // 这里要decimal类型的参数
            @"pay_type":@"2" // 支付方式 1微信 2支付宝 3银联
        };
        [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"buyorder" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
        } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineCartCell"];
    cell.isSelected = [self.selectArray containsObject:self.dataArray[indexPath.row][@"id"]];
    cell.dataDic = self.dataArray[indexPath.row];
    cell.cellIndexPath = indexPath;
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 120;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    [self pushVideoDetailVCWithID:dataDic[@"id"]];
}

- (BOOL)array:(NSMutableArray *)array1 isEqualTo:(NSMutableArray *)array2 {
    if (array1.count != array2.count) {
        return NO;
    }
    for (NSIndexPath *str in array1) {
        if (![array2 containsObject:str]) {
            return NO;
        }
    }
    for (NSIndexPath *str in array2) {
        if (![array1 containsObject:str]) {
            return NO;
        }
    }
    return YES;
}

- (void)MineCartCellTapSelectBtn:(NSIndexPath *)cellIndexPath
{
    MineCartCell *cell = (MineCartCell *)[self.tableView cellForRowAtIndexPath:cellIndexPath];
    cell.isSelected = !cell.isSelected;
    NSDecimalNumber *priceToadd = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",self.dataArray[cellIndexPath.row][@"price"]]];
    if ([self.selectArray containsObject:self.dataArray[cellIndexPath.row][@"id"]]) {
        [self.selectArray removeObject:self.dataArray[cellIndexPath.row][@"id"]];
        
        self.moneyString = [self.moneyString decimalNumberBySubtracting:priceToadd];
    } else {
        [self.selectArray addObject:self.dataArray[cellIndexPath.row][@"id"]];
        
        self.moneyString = [self.moneyString decimalNumberByAdding:priceToadd];
    }
    if ([self array:self.selectArray isEqualTo:self.allIDArray]) {
        self.selectAllBtn.selected = YES;
    } else {
        self.selectAllBtn.selected = NO;
    }

    NSString *priceString = [NSString stringWithFormat:@"合计：%@元",[self.moneyString stringValue]];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceString];
    [string addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:118/255.0 blue:0/255.0 alpha:1.0]} range:NSMakeRange(2, [[self.moneyString stringValue] length]+ 1)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange([[self.moneyString stringValue] length]+3, 1)];
    [string addAttributes:@{NSForegroundColorAttributeName: RGB_VALUE(0x989898)} range:NSMakeRange(0, 3)];
    self.moneyLabel.attributedText = string;
    [self.tableView reloadData];
}
@end
